"""
患者数据模型
"""
from sqlalchemy import Column, Integer, String, SmallInteger, DateTime, Boolean, Numeric, ForeignKey, Text
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from  core.database import Base


class Patient(Base):
    """患者表"""
    __tablename__ = "patients"
    
    id = Column(Integer, primary_key=True, index=True, comment="患者ID")
    name = Column(String(100), nullable=False, index=True, comment="患者姓名")
    phone = Column(String(20), nullable=True, unique=True, index=True, comment="手机号")
    id_card = Column(String(25), nullable=True, unique=True, comment="身份证号")
    gender = Column(String(10), nullable=True, comment="性别")
    age = Column(Integer, nullable=True, comment="年龄")
    height = Column(Numeric(5, 2), nullable=True, comment="身高(cm)")
    weight = Column(Numeric(5, 2), nullable=True, comment="体重(kg)")
    handedness = Column(String(10), nullable=True, comment="惯用手")
    avatar = Column(Text, nullable=True, comment="头像URL")
    
    # 疾病史
    diabetes = Column(Boolean, nullable=False, default=False, comment="糖尿病")
    hypertension = Column(Boolean, nullable=False, default=False, comment="高血压")
    hyperlipidemia = Column(Boolean, nullable=False, default=False, comment="高血脂")
    stroke_history = Column(Boolean, nullable=False, default=False, comment="卒中史")
    heart_disease = Column(Boolean, nullable=False, default=False, comment="心脏病")
    atrial_fibrillation = Column(Boolean, nullable=False, default=False, comment="房颤")
    sleep_apnea = Column(Boolean, nullable=False, default=False, comment="睡眠呼吸暂停")
    
    # 吸烟史
    has_smoking_history = Column(Boolean, nullable=False, default=False, comment="有吸烟史")
    smoking_amount = Column(Integer, nullable=True, comment="吸烟量(支/天)")
    smoking_years = Column(Integer, nullable=True, comment="吸烟年限")
    has_quit_smoking = Column(Boolean, nullable=True, comment="已戒烟")
    
    # 饮酒史
    has_drinking_history = Column(Boolean, nullable=False, default=False, comment="有饮酒史")
    drinking_amount = Column(Integer, nullable=True, comment="饮酒量(ml/天)")
    drinking_years = Column(Integer, nullable=True, comment="饮酒年限")
    has_quit_drinking = Column(Boolean, nullable=True, comment="已戒酒")
    
    # 关联医生
    doctor_id = Column(Integer, ForeignKey("doctors.id"), nullable=True, comment="负责医生ID")
    
    status = Column(SmallInteger, nullable=False, default=1, comment="状态 1-正常 0-禁用")
    created_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        comment="创建时间"
    )
    updated_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        onupdate=func.now(),
        comment="更新时间"
    )
    
    # 关系
    doctor = relationship("Doctor", back_populates="patients")
    medical_records = relationship("MedicalRecord", back_populates="patient")
    
    def __repr__(self):
        return f"<Patient(id={self.id}, name={self.name}, phone={self.phone})>"

